package com.bonuo.saas.service.impl;

import com.bonuo.saas.domain.WorkOrder;
import com.bonuo.saas.domain.WorkorderSynergy;
import com.bonuo.saas.mapper.WorkOrderMapper;
import com.bonuo.saas.mapper.WorkorderSynergyMapper;
import com.bonuo.saas.service.WorkOrderService;
import com.ruoyi.common.annotation.DataScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class WorkOrderServiceImpl implements WorkOrderService {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private WorkorderSynergyMapper workorderSynergyMapper;

    @DataScope(userAlias = "w")
    @Override
    public List<WorkOrder> selectWorkOrderList(WorkOrder workOrder) {
        return workOrderMapper.selectWorkOrderList(workOrder);
    }

    @Override
    @Transactional
    public int insertWorkOrder(WorkOrder workOrder) {
        // 添加工单
        int i = workOrderMapper.insertWorkOrder(workOrder);
        // 添加工单和协同人关系表
        for (Integer synergyId : workOrder.getSynergyIds()) {
            WorkorderSynergy workorderSynergy = new WorkorderSynergy(null, workOrder.getId(), synergyId);
            workorderSynergyMapper.insertWorkorderSynergy(workorderSynergy);
        }

        return i;
    }

    @Override
    @Transactional
    public int updateWorkOrder(WorkOrder workOrder) {
        // 更新工单
        int i = workOrderMapper.updateWorkOrder(workOrder);

        // 查询该工单的旧协同人ID列表
        List<Integer> oldSynergies = workorderSynergyMapper.selectSynergyUserIdsByWorkorderId(workOrder.getId());
        // 处理旧列表为空的情况
        oldSynergies = (oldSynergies == null) ? Collections.emptyList() : oldSynergies;

        // 获取前端新协同人列表，处理为空的情况
        List<Integer> newSynergies = workOrder.getSynergyIds();
        newSynergies = (newSynergies == null) ? Collections.emptyList() : newSynergies;

        // 转为Set忽略顺序和重复，判断是否需要更新
        Set<Integer> oldSet = new HashSet<>(oldSynergies);
        Set<Integer> newSet = new HashSet<>(newSynergies);
        if (oldSet.equals(newSet)) {
            // 元素相同（忽略顺序），不操作关联表
            return i;
        }

        // 元素不同，执行删除和新增
        workorderSynergyMapper.deleteWorkorderSynergyByWorkorderId(workOrder.getId());
        for (Integer synergyId : newSynergies) {
            WorkorderSynergy workorderSynergy = new WorkorderSynergy(null, workOrder.getId(), synergyId);
            workorderSynergyMapper.insertWorkorderSynergy(workorderSynergy);
        }

        return i;
    }


    @Override
    @Transactional
    public int deleteWorkOrderById(Integer id) {
        // 删除工单
        int i = workOrderMapper.deleteWorkOrderById(id);
        // 删除工单和协同人关系表
        workorderSynergyMapper.deleteWorkorderSynergyByWorkorderId(id);
        return i;
    }
}
